/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/9/26 10:49
 */
package com.gitee.mechanic.web.utils;

import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Request 工具类
 *
 * @author mechanic
 */
public class RequestUtils {
    /**
     * 获取 HttpServletRequest
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        Assert.notNull(servletRequestAttributes, "request must not be null.");
        return servletRequestAttributes.getRequest();
    }

    /**
     * 获取当前请求中的根 URL。格式 http://domain:port
     *
     * @param request HttpServletRequest
     * @return URL
     */
    public static String getRootURL(HttpServletRequest request) {
        return getRootURLasStringBuffer(request).toString();
    }

    /**
     * 获取当前请求中的带上下文路径的 URL。格式 http://domain:port/contextPath
     *
     * @param request HttpServletRequest
     * @return URL
     */
    public static String getContextURL(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        return getRootURL(request) + contextPath + "/";
    }

    /**
     * 获取当前请求中的不包含协议的 URL。格式 domain:port/contextPath
     *
     * @param request HttpServletRequest
     * @return URL
     */
    public static String getNoSchemeContextURL(HttpServletRequest request) {
        return request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
    }

    /**
     * 获取当前请求中的根 URL
     *
     * @param request HttpServletRequest
     * @return URL
     */
    private static StringBuffer getRootURLasStringBuffer(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        StringBuffer requestURL = request.getRequestURL();
        return requestURL.delete(requestURL.indexOf(contextPath), requestURL.length()).append("/");
    }
}
